package his.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import his.entity.*;
import his.persistence.*;
import his.service.QueryCaseHistoryService;
import his.vo.PrescriptionsFilled;
import his.vo.RegisterVO;
import his.vo.ReturnDrugsVO;
import his.vo.ReturnRegistVO;
import org.example.his.common.api.CommonResponse;
import org.example.his.common.auth.JwtAuth;
import org.example.medicalstaff.utils.DateStringFormat;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Service
public class QueryCaseHistoryServiceImpl implements QueryCaseHistoryService {

    @Autowired
    private PatientMapper patientMapper;
    @Autowired
    private RegisterMapper registerMapper;
    @Autowired
    private MedicalRecordMapper medicalRecordMapper;
    @Autowired
    private PrescriptionMapper prescriptionMapper;
    @Autowired
    private PrescriptionDetailedMapper prescriptionDetailedMapper;
    @Autowired
    private DrugsMapper drugsMapper;
    @Autowired
    private DepartmentMapper departmentMapper;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private RegistLevelMapper registLevelMapper;
    @Autowired
    private VoucherMapper voucherMapper;
    @Autowired
    private CheckApplyMapper checkApplyMapper;
    @Autowired
    private PatientCostsMapper patientCostsMapper;

    /**
     * API1 查询历史病历
     */
    public CommonResponse<List<RegisterVO>> queryCaseHistory(
            String token
    ){
        List<RegisterVO> registerVOList = new ArrayList<>();
        //token转化为openID
        String OpenID = JwtAuth.jwtDecrypt(token);
        //根据OpenID查找CaseNumber
        QueryWrapper<Patient> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("OpenID",OpenID);
        Patient patient = patientMapper.selectOne(queryWrapper);
        if (patient == null){
            return CommonResponse.createForError("查找失败，patient为空");
        }
        String CaseNumber = patient.getCaseNumber();
        //根据CaseNumber查找Register表里的内容
        QueryWrapper<Register> registerQueryWrapper = new QueryWrapper<>();
        registerQueryWrapper.eq("CaseNumber",CaseNumber);
        List<Register> registerList = registerMapper.selectList(registerQueryWrapper);
        if (registerList == null){
            return CommonResponse.createForError("查找失败，register为空");
        }
        for (int i = 0; i < registerList.size(); i++) {
            RegisterVO registerVO = new RegisterVO();
            //Gender
            if (registerList.get(i).getGender()==71){
                //男
                registerVO.setGender("男");
            }else{
                registerVO.setGender("女");
            }
            //visitDate
            Date myDate = registerList.get(i).getVisitDate();
            SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd");
            String strDate1 = sdf1.format(myDate);
            //这里要把时间转换为Date再存入
            //设置时间格式
            String pattern = "yyyy-MM-dd";
            Date date = DateStringFormat.parseDateTimeString(strDate1,pattern);
            System.out.println(strDate1);
            registerVO.setVisitDate(date);
            System.out.println("strDate1:" + strDate1);
            System.out.println(registerVO.getVisitDate());
            //noon
            registerVO.setNoon(registerList.get(i).getNoon());
            //本次挂号科室名，根据科室ID查科室名
            QueryWrapper<Department> departmentQueryWrapper = new QueryWrapper<>();
            departmentQueryWrapper.eq("ID",registerList.get(i).getDeptID());
            Department department = departmentMapper.selectOne(departmentQueryWrapper);
            registerVO.setDeptName(department.getDeptName());
            //本次挂号医生名
            QueryWrapper<User> userQueryWrapper = new QueryWrapper<>();
            userQueryWrapper.eq("ID",registerList.get(i).getUserID());
            User user = userMapper.selectOne(userQueryWrapper);
            registerVO.setUserName(user.getUserName());
            //本次挂号级别
            QueryWrapper<RegistLevel> registLevelQueryWrapper = new QueryWrapper<>();
            registLevelQueryWrapper.eq("ID",registerList.get(i).getRegistLeID());
            RegistLevel registLevel = registLevelMapper.selectOne(registLevelQueryWrapper);
            registerVO.setRegistLeID(registLevel.getRegistName());
            //是否要病历本
            if (registerList.get(i).getIsBook()=='1'){
                registerVO.setIsBook("是");
            }else{
                registerVO.setIsBook("否");
            }
            //挂号时间
            registerVO.setRegistTime(registerList.get(i).getRegistTime());
            registerVOList.add(registerVO);
        }
        if (registerVOList == null){
            return CommonResponse.createForError("查找失败，registerList为空");
        }else{
            return CommonResponse.createForSuccess("查找成功",registerVOList);
        }
    }

    /**
     * API2 查看已开处方
     */
    public CommonResponse<List<PrescriptionsFilled>> viewPrescriptionsFilled(
            String token
    ){
        List<PrescriptionsFilled> prescriptionsFilledList = new ArrayList<>();
        //token转化为openID
        String OpenID = JwtAuth.jwtDecrypt(token);
        //根据OpenID查找CaseNumber
        QueryWrapper<Patient> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("OpenID",OpenID);
        Patient patient = patientMapper.selectOne(queryWrapper);
        if (patient == null){
            return CommonResponse.createForError("查找失败，patient为空");
        }
        String CaseNumber = patient.getCaseNumber();
        //根据CaseNumber查找MedicalRecord表找到MedicalID（ID属性）,RegistID属性
        QueryWrapper<MedicalRecord> medicalRecordQueryWrapper = new QueryWrapper<>();
        medicalRecordQueryWrapper.eq("CaseNumber",CaseNumber);
        List<MedicalRecord> medicalRecordList = medicalRecordMapper.selectList(medicalRecordQueryWrapper);
        if (medicalRecordList == null){
            return CommonResponse.createForError("查找失败，medicalRecordList为空");
        }
        for (int i = 0; i < medicalRecordList.size(); i++) {
            int MedicalID = medicalRecordList.get(i).getID();
            int RegistID = medicalRecordList.get(i).getRegistID();
            QueryWrapper<Prescripition> prescripitionQueryWrapper = new QueryWrapper<>();
            prescripitionQueryWrapper.eq("MedicalID",MedicalID);
            prescripitionQueryWrapper.eq("RegistID",RegistID);
            List<Prescripition> prescripitionList = prescriptionMapper.selectList(prescripitionQueryWrapper);
            if (prescripitionList == null){
                return CommonResponse.createForError("查找失败，prescripitionList为空");
            }
            for (int j = 0; j < prescripitionList.size(); j++) {
                int PreID = prescripitionList.get(j).getID();
                QueryWrapper<PrescriptionDetailed> prescriptionDetailedQueryWrapper = new QueryWrapper<>();
                prescriptionDetailedQueryWrapper.eq("PrescriptionID",PreID);
                List<PrescriptionDetailed> prescriptionDetailedList = prescriptionDetailedMapper.selectList(prescriptionDetailedQueryWrapper);
                if (prescriptionDetailedList == null){
                    return CommonResponse.createForError("查找失败，prescriptionDetailedList为空");
                }
                for (int k = 0; k < prescriptionDetailedList.size(); k++) {
                    //这里创建一个vo
                    PrescriptionsFilled prescriptionsFilled = new PrescriptionsFilled();
                    //获取prescriptionDetailed记录的值
                    int DrugsID = prescriptionDetailedList.get(k).getDrugsID();
                    String DrugsUsage = prescriptionDetailedList.get(k).getDrugsUsage();
                    String Dosage = prescriptionDetailedList.get(k).getDosage();
                    String Frequency = prescriptionDetailedList.get(k).getFrequency();
                    BigDecimal Amount = prescriptionDetailedList.get(k).getAmount();
                    int State = prescriptionDetailedList.get(k).getState();
                    QueryWrapper<Drugs> drugsQueryWrapper = new QueryWrapper<>();
                    drugsQueryWrapper.eq("ID",DrugsID);
                    Drugs drugs = drugsMapper.selectOne(drugsQueryWrapper);
                    if (drugs == null){
                        return CommonResponse.createForError("查找失败，drugs为空");
                    }
                    String DrugsName = drugs.getDrugsName();
                    prescriptionsFilled.setAmount(Amount);
                    prescriptionsFilled.setDosage(Dosage);
                    prescriptionsFilled.setDrugsUsage(DrugsUsage);
                    prescriptionsFilled.setFrequency(Frequency);
                    prescriptionsFilled.setState(State);
                    prescriptionsFilled.setDrugsName(DrugsName);
                    prescriptionsFilledList.add(prescriptionsFilled);
                }
            }
        }
        if (prescriptionsFilledList != null){
            return CommonResponse.createForSuccess("查找成功",prescriptionsFilledList);
        }else{
            return CommonResponse.createForError("查找失败，找不到处方表");
        }
    }

    /**
     * API3 退号
     */
    public CommonResponse<String> del_regist(String CaseNumber , int VisitState){
        if (VisitState != 1){
            return CommonResponse.createForError("退号失败，状态不正确");
        }
        QueryWrapper<Register> registerQueryWrapper = new QueryWrapper<>();
        registerQueryWrapper.eq("CaseNumber" , CaseNumber).eq("VisitState" , VisitState);
        int result = registerMapper.delete(registerQueryWrapper);
        if (result == 0){
            return CommonResponse.createForError("退号失败，找不到号");
        }else{
            return CommonResponse.createForSuccess("退号成功");
        }
    }

    /**
     * API4 退费
     */
    public CommonResponse<String> refunds(int RegistID , String CaseNumber,int ItemID, BigDecimal price, int ItemType, String Status ,BigDecimal totalPrice) {
        if(Status.equals("已收费")){
            //根据CaseNumber RegistID找到对应的userID
            QueryWrapper<Register> registerQueryWrapper = new QueryWrapper<>();
            registerQueryWrapper.eq("CaseNumber" , CaseNumber).eq("ID" , RegistID);
            Register register = registerMapper.selectOne(registerQueryWrapper);
            int registerID = register.getRegisterID();
            //获取到挂号员的id
            QueryWrapper<User> userQueryWrapper = new QueryWrapper<>();
            userQueryWrapper.eq("ID" , registerID);
            User register_people = userMapper.selectOne(userQueryWrapper);
            //生成对应的凭证 voucher 一个项目一个
        /*
        对应逻辑，生成voucher号,添加对应的信息
         */
            Voucher voucher = new Voucher();
            voucher.setUserID(register_people.getID());
            voucher.setMoney(totalPrice);
            voucher.setCreationTime(new Date());
            voucher.setItemID(ItemID);
            List<String> voucherNum = voucherMapper.getVoucherNum();
            //设置为最小值 方便之后更新
            int maxVoucherNum = Integer.MIN_VALUE;
            for (String age : voucherNum) {
                int VoucherNumInt = Integer.parseInt(age);
                if (VoucherNumInt > maxVoucherNum) {
                    maxVoucherNum = VoucherNumInt;
                }
            }
            voucher.setVoucherNum(Integer.toString(maxVoucherNum+1));
            //生成新的voucher添加到表中
            voucherMapper.insert(voucher);
            //更改checkapply中的状态
            QueryWrapper<CheckApply> checkApplyQueryWrapper = new QueryWrapper<>();
            checkApplyQueryWrapper.eq("ItemID" ,ItemID ).eq("RegistID" , RegistID);
            CheckApply checkApply = checkApplyMapper.selectOne(checkApplyQueryWrapper);
            checkApply.setState(0);
            //若项目为药品 更改处方表中的各药品的状态
            if(ItemType == 2){
                QueryWrapper<Prescripition> prescriptionQueryWrapper = new QueryWrapper<>();
                prescriptionQueryWrapper.eq("RegistID" , RegistID);
                List<Prescripition> prescriptions = prescriptionMapper.selectList(prescriptionQueryWrapper);
                QueryWrapper<PrescriptionDetailed> prescriptionDetailedQueryWrapper = new QueryWrapper<>();
                for(int i=0 ; i < prescriptions.size() ; i++){
                    int id = prescriptions.get(i).getID();
                    prescriptionDetailedQueryWrapper.eq("PrescriptionID" , id).eq("DrugsID" , ItemID);
                    PrescriptionDetailed prescriptionDetailed = prescriptionDetailedMapper.selectOne(prescriptionDetailedQueryWrapper);
                    prescriptionDetailed.setState(0);
                }
            }
            return CommonResponse.createForSuccess("退费成功");
        }
        else return CommonResponse.createForError("当前状态无法退费");
    }

    /**
     * API5 退药
     */
    public CommonResponse<String> returnMedical(
            String PrescriptionID
    ){
        QueryWrapper<Prescripition> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("ID",PrescriptionID);
        //先判断是否是暂存状态
        Prescripition prescripition = prescriptionMapper.selectOne(queryWrapper);
        if (prescripition.getPrescriptionState()!=1){
            return CommonResponse.createForError("删除失败，不是暂存状态");
        }
        //然后删除明细
        int preID = prescripition.getID();
        QueryWrapper<PrescriptionDetailed> queryWrapper1 = new QueryWrapper<>();
        queryWrapper1.eq("PrescriptionID",preID);
        prescriptionDetailedMapper.delete(queryWrapper1);
        //然后删除处方
        int result = prescriptionMapper.delete(queryWrapper);
        if (result == 0){
            return CommonResponse.createForError("删除失败，属性不匹配");
        }else{
            return CommonResponse.createForSuccess("删除成功");
        }
    }

    /**
     * API7 删除未开立项目
     */
    public CommonResponse<String> del_no_init_pro(
            int MedicalID,
            int RegistID,
            int ItemID
    ){
        QueryWrapper<CheckApply> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("MedicalID",MedicalID);
        queryWrapper.eq("RegistID",RegistID);
        queryWrapper.eq("ItemID",ItemID);
        CheckApply checkApply = checkApplyMapper.selectOne(queryWrapper);
        if (checkApply.getState() != 1){
            //说明不是暂存状态
            return CommonResponse.createForError("删除未开立项目失败，不是暂存状态！");
        }
        int result = checkApplyMapper.delete(queryWrapper);
        if (result == 0){
            return CommonResponse.createForError("删除未开立项目失败");
        }else {
            return CommonResponse.createForSuccess("删除未开立项目成功");
        }
    }



    /**
     * API7 获取挂号消费记录 用于退号的项目
     */
    public CommonResponse<List<ReturnRegistVO>> getPatientCostsRegist(
            String token
    ){
        List<ReturnRegistVO> returnRegistVOS = new ArrayList<>();
        //根据token获取openID
        String OpenID = JwtAuth.jwtDecrypt(token);
        //根据OpenID查找CaseNumber
        QueryWrapper<Patient> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("OpenID",OpenID);
        Patient patient = patientMapper.selectOne(queryWrapper);
        if (patient == null){
            return CommonResponse.createForError("查找失败，patient为空");
        }
        String CaseNumber = patient.getCaseNumber();
        //根据CaseNumber查找Register表里的内容
        QueryWrapper<Register> registerQueryWrapper = new QueryWrapper<>();
        registerQueryWrapper.eq("CaseNumber",CaseNumber);
        List<Register> registerList = registerMapper.selectList(registerQueryWrapper);
        if (registerList == null){
            return CommonResponse.createForError("查找失败，register为空");
        }
        for (int i = 0; i < registerList.size(); i++) {
            //根据每一条Regist去找patientCosts里的记录
            int ReID = registerList.get(i).getId();
            QueryWrapper<PatientCosts> patientCostsQueryWrapper = new QueryWrapper<>();
            patientCostsQueryWrapper.eq("RegistID",ReID);
            List<PatientCosts> patientCostsList = new ArrayList<>();
            patientCostsList = patientCostsMapper.selectList(patientCostsQueryWrapper);
            if (patientCostsList != null){
                for (int j = 0; j < patientCostsList.size(); j++) {
                    if (patientCostsList.get(j).getName().equals("挂号费")){
                        ReturnRegistVO returnRegistVO = new ReturnRegistVO();
                        returnRegistVO.setRegistID(patientCostsList.get(j).getRegistID());
                        returnRegistVO.setName(patientCostsList.get(j).getName());
                        returnRegistVO.setPrice(patientCostsList.get(j).getPrice());
                        returnRegistVO.setAmount(patientCostsList.get(j).getAmount());
                        //接下来获取状态，保存在Register表里面。
                        returnRegistVO.setVisitState(registerList.get(i).getVisitState());
                        returnRegistVOS.add(returnRegistVO);
                    }
                }
            }
        }
        if (registerList == null){
            return CommonResponse.createForError("没有挂号费");
        }else{
            return CommonResponse.createForSuccess("有挂号费",returnRegistVOS);
        }
    }


    /**
     * API8 获取药品的消费记录 用于退号的项目
     */
    public CommonResponse<List<PrescriptionsFilled>> getPatientCostsDrugs(
            String token
    ){
        List<PrescriptionsFilled> prescriptionsFilledList = new ArrayList<>();
        //token转化为openID
        String OpenID = JwtAuth.jwtDecrypt(token);
        //根据OpenID查找CaseNumber
        QueryWrapper<Patient> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("OpenID",OpenID);
        Patient patient = patientMapper.selectOne(queryWrapper);
        if (patient == null){
            return CommonResponse.createForError("查找失败，patient为空");
        }
        String CaseNumber = patient.getCaseNumber();
        //根据CaseNumber查找MedicalRecord表找到MedicalID（ID属性）,RegistID属性
        QueryWrapper<MedicalRecord> medicalRecordQueryWrapper = new QueryWrapper<>();
        medicalRecordQueryWrapper.eq("CaseNumber",CaseNumber);
        List<MedicalRecord> medicalRecordList = medicalRecordMapper.selectList(medicalRecordQueryWrapper);
        if (medicalRecordList == null){
            return CommonResponse.createForError("查找失败，medicalRecordList为空");
        }
        for (int i = 0; i < medicalRecordList.size(); i++) {
            int MedicalID = medicalRecordList.get(i).getID();
            int RegistID = medicalRecordList.get(i).getRegistID();
            QueryWrapper<Prescripition> prescripitionQueryWrapper = new QueryWrapper<>();
            prescripitionQueryWrapper.eq("MedicalID",MedicalID);
            prescripitionQueryWrapper.eq("RegistID",RegistID);
            List<Prescripition> prescripitionList = prescriptionMapper.selectList(prescripitionQueryWrapper);
            if (prescripitionList == null){
                return CommonResponse.createForError("查找失败，prescripitionList为空");
            }
            for (int j = 0; j < prescripitionList.size(); j++) {
                int PreID = prescripitionList.get(j).getID();
                QueryWrapper<PrescriptionDetailed> prescriptionDetailedQueryWrapper = new QueryWrapper<>();
                prescriptionDetailedQueryWrapper.eq("PrescriptionID",PreID);
                List<PrescriptionDetailed> prescriptionDetailedList = prescriptionDetailedMapper.selectList(prescriptionDetailedQueryWrapper);
                if (prescriptionDetailedList == null){
                    return CommonResponse.createForError("查找失败，prescriptionDetailedList为空");
                }
                for (int k = 0; k < prescriptionDetailedList.size(); k++) {
                    //这里创建一个vo
                    PrescriptionsFilled prescriptionsFilled = new PrescriptionsFilled();
                    //获取prescriptionDetailed记录的值
                    int DrugsID = prescriptionDetailedList.get(k).getDrugsID();
                    String DrugsUsage = prescriptionDetailedList.get(k).getDrugsUsage();
                    String Dosage = prescriptionDetailedList.get(k).getDosage();
                    String Frequency = prescriptionDetailedList.get(k).getFrequency();
                    BigDecimal Amount = prescriptionDetailedList.get(k).getAmount();
                    int State = prescriptionDetailedList.get(k).getState();
                    QueryWrapper<Drugs> drugsQueryWrapper = new QueryWrapper<>();
                    drugsQueryWrapper.eq("ID",DrugsID);
                    Drugs drugs = drugsMapper.selectOne(drugsQueryWrapper);
                    if (drugs == null){
                        return CommonResponse.createForError("查找失败，drugs为空");
                    }
                    String DrugsName = drugs.getDrugsName();
                    prescriptionsFilled.setDrugsPrice(drugs.getDrugsPrice());//获取单价
                    prescriptionsFilled.setAmount(Amount);
                    prescriptionsFilled.setDosage(Dosage);
                    prescriptionsFilled.setDrugsUsage(DrugsUsage);
                    prescriptionsFilled.setFrequency(Frequency);
                    prescriptionsFilled.setState(State);
                    prescriptionsFilled.setDrugsName(DrugsName);
                    prescriptionsFilledList.add(prescriptionsFilled);
                }
            }
        }
        if (prescriptionsFilledList != null){
            return CommonResponse.createForSuccess("查找成功",prescriptionsFilledList);
        }else{
            return CommonResponse.createForError("查找失败，找不到处方表");
        }
//        List<ReturnDrugsVO> returnDrugsVOList = new ArrayList<>();
//        List<PrescriptionsFilled> prescriptionsFilledList = new ArrayList<>();
//        //token转化为openID
//        String OpenID = JwtAuth.jwtDecrypt(token);
//        //根据OpenID查找CaseNumber
//        QueryWrapper<Patient> queryWrapper = new QueryWrapper<>();
//        queryWrapper.eq("OpenID",OpenID);
//        Patient patient = patientMapper.selectOne(queryWrapper);
//        if (patient == null){
//            return CommonResponse.createForError("查找失败，patient为空");
//        }
//        String CaseNumber = patient.getCaseNumber();
//        //根据CaseNumber查找Register表里的内容
//        QueryWrapper<Register> registerQueryWrapper = new QueryWrapper<>();
//        registerQueryWrapper.eq("CaseNumber",CaseNumber);
//        List<Register> registerList = registerMapper.selectList(registerQueryWrapper);
//        if (registerList == null){
//            return CommonResponse.createForError("查找失败，register为空");
//        }
//        for (int i = 0; i < registerList.size(); i++) {
//            //根据每一条Regist去找patientCosts里的记录
//            int ReID = registerList.get(i).getId();
//            QueryWrapper<PatientCosts> patientCostsQueryWrapper = new QueryWrapper<>();
//            patientCostsQueryWrapper.eq("RegistID",ReID);
//            List<PatientCosts> patientCostsList = new ArrayList<>();
//            patientCostsList = patientCostsMapper.selectList(patientCostsQueryWrapper);
//            if (patientCostsList != null){
//                for (int j = 0; j < patientCostsList.size(); j++) {
//                    if (patientCostsList.get(j).getItemType()==2){
//                        //说明是药品
//                        ReturnDrugsVO returnDrugsVO = new ReturnDrugsVO();
//                        returnDrugsVO.setRegistID(patientCostsList.get(j).getRegistID());
//                        returnDrugsVO.setName(patientCostsList.get(j).getName());
//                        returnDrugsVO.setPrice(patientCostsList.get(j).getPrice());
//                        returnDrugsVO.setAmount(patientCostsList.get(j).getAmount());
//                        //接下来获取状态，保存在PrescriptionDetailed 表里面。
//
//                        returnDrugsVOList.add(returnDrugsVO);
//                    }
//                }
//            }
//        }

    }

}
